using System;
using System.Collections.Generic;
using System.ComponentModel;

using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Net;
using System.Collections;
using System.Text.RegularExpressions;
using System.Security.Cryptography;
using System.Xml;
using CodePlex.SpaceBlock;
using System.Reflection;
using System.Diagnostics;
using CodePlex.SpaceBlock.FS;
using CodePlex.Resourceful;
using CodePlex.SpaceBlock.UI.Controls.Explore;
using CodePlex.SpaceBlock.UI.Controls.Tools;
using CodePlex.SpaceBlock.UI.Controls.Transfer;
using CodePlex.SpaceBlock.UI.Controls.Log;


namespace CodePlex.SpaceBlock.UI.Controls
{
    public partial class MainForm : CodePlex.SpaceBlock.UI.Controls.BaseForm
    {

       
        public MainForm()
        {
            InitializeComponent();

            this.StartPosition = FormStartPosition.CenterScreen;

            UIManager.Instance = new UIManager(_smallIcons,_statusBarLabel,this);

           
            if (!AuthUtils.AppStartup(this))
            {
                this.Close();
            }

            this.FormClosing += delegate(object sender, FormClosingEventArgs e)
            {
                if (UIManager.Instance.JobManager.IsBusy)
                {
                    if (!UIUtils.YesNo(this,
                        UIManager.Instance.GetIcon(UIConstants.ImageHints.Information),
                        Properties.Messages.MainForm_InterrupTransfer_Title,
                        Properties.Messages.MainForm_InterrupTransfer_Description))
                    {
                        e.Cancel = true;
                        return;
                    }
                }
            };

           
        }

        public bool ShowToolsOptions(bool zombieMode)
        {
            OptionsForm dialog = new OptionsForm();
            dialog.Icon = UIManager.Instance.GetIcon(UIConstants.ImageHints.Options);
            dialog.Initialize(this, AuthUtils.FileSystemManager, zombieMode);
            dialog.StartPosition = FormStartPosition.CenterScreen;
            DialogResult rt = dialog.ShowDialog(this);

            if (rt == DialogResult.Cancel && !AuthUtils.FileSystemManager.IsValid)
            {
                this.Close();
                return false;
            }

            return true;
        }






        private void DelayLoad()
        {

            _menu.ImageList = UIManager.Instance.SmallImageList;


            _exitMenuItem.GetCurrentParent().ImageList = UIManager.Instance.SmallImageList;
            _exitMenuItem.ImageIndex = UIManager.Instance.GetSmallImageListIndex(UIConstants.ImageHints.ExitArrow);
            _exitMenuItem.Click += delegate
            {
                Application.Exit();
            };

          



            _whatsNewMenuItem.GetCurrentParent().ImageList = UIManager.Instance.SmallImageList;
            _whatsNewMenuItem.ImageIndex = UIManager.Instance.GetSmallImageListIndex(UIConstants.ImageHints.SpaceBlock);
            _whatsNewMenuItem.Click += delegate
            {
                Process.Start(UIConstants.Urls.WhatsNewUrl);
            };


            _aboutSpaceBlockMenuItem.GetCurrentParent().ImageList = UIManager.Instance.SmallImageList;
            _aboutSpaceBlockMenuItem.ImageIndex = UIManager.Instance.GetSmallImageListIndex(UIConstants.ImageHints.Gear);
            _aboutSpaceBlockMenuItem.Click += delegate
            {
                Process.Start(Properties.Messages.Urls_About_SpaceBlock);
            };

            _aboutResourcefulMenuItem.GetCurrentParent().ImageList = UIManager.Instance.SmallImageList;
            _aboutResourcefulMenuItem.ImageIndex = UIManager.Instance.GetSmallImageListIndex(UIConstants.ImageHints.Gear);
            _aboutResourcefulMenuItem.Click += delegate
            {
                Process.Start(Properties.Messages.Urls_About_Resourceful);
            };

            _resetMenuItem.GetCurrentParent().ImageList = UIManager.Instance.SmallImageList;
            _resetMenuItem.ImageIndex = UIManager.Instance.GetSmallImageListIndex(UIConstants.ImageHints.Key);
            _resetMenuItem.Click += delegate
            {
                AuthUtils.ResetMasterPassword(this, true, false);
            };

            _optionsMenuItem.GetCurrentParent().ImageList = UIManager.Instance.SmallImageList;
            _optionsMenuItem.ImageIndex = UIManager.Instance.GetSmallImageListIndex(UIConstants.ImageHints.Options);
            _optionsMenuItem.Click += delegate
            {
                ShowToolsOptions(false);
            };
         

            this.LoadViews();

            UIUtils.MinimizeToTray(this, UIManager.Instance.GetIcon(UIConstants.ImageHints.SpaceBlock));

            this.Activate();




            // show "what's new" form if this is a new release
            if (Properties.Settings.Default.WhatsNewVersion != UIConstants.ApplicationFileVersion)
            {
                WhatsNewForm f = new WhatsNewForm();
                Properties.Settings.Default.WhatsNewVersion = UIConstants.ApplicationFileVersion;
                Properties.Settings.Default.Save();
                f.ShowDialog(this);
            }




        }



        private void LoadViews()
        {
          //  this.SuspendLayout();
            _viewPanel.Controls.Clear();

            // construct views
            List<IView> views = new List<IView>();
            views.Add(new ExploreView());
            views.Add(new TransfersView());
            views.Add(new LogView());


            _viewGrid.SelectionChanged += delegate
            {
                if (_viewGrid.SelectedRows.Count != 1)
                {
                    return;
                }

                IView v = _viewGrid.SelectedRows[0].Tag as IView;

                foreach (Control c in _viewPanel.Controls)
                {

                    c.Visible = false;
                }
                v.Control.Visible = true;

            };


            // create view controls
            foreach (IView view in views)
            {
                Control c = view.Control;
                c.Tag = view;
                UIUtils.FillWith(_viewPanel, c);
            }

            // initialize view controls
            foreach (IView view in views)
            {
                view.Initialize();
            }



            _viewGrid.MultiSelect = false;
            _viewGrid.AllowUserToResizeColumns = false;
            _viewGrid.Cursor = Cursors.Hand;
            _viewGrid.SelectionMode = DataGridViewSelectionMode.FullRowSelect;
            _viewGrid.StandardTab = true;


            // workaround designer column auto-add
            while (_viewGrid.Columns.Count > 1)
            {
                _viewGrid.Columns.RemoveAt(1);
            }

            DataGridViewColumn imageColumn = _viewGrid.Columns[0];
            imageColumn.DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter;
            imageColumn.Width = 28;


            DataGridViewColumn textColumn = _viewGrid.AddColumnText("Name", 100);
            textColumn.AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill;
            textColumn.DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleLeft;
            textColumn.DefaultCellStyle.Padding = new Padding(0, 4, 0, 4);

            _viewGrid.RowTemplate.MinimumHeight = 26;
            _viewGrid.RowTemplate.DividerHeight = 1;


            _viewGrid.Visible = true;

           // this.ResumeLayout();



            // add view grid items
            foreach (IView view in views)
            {
                DataGridViewRow newRow = _viewGrid.AddRow(view, UIManager.Instance.GetSmallImage(view.ImageHint), view.Caption);
                foreach (DataGridViewCell c in newRow.Cells)
                {
                    c.ToolTipText = view.Tooltip;
                }
            }



            // add view menu items
            foreach (IView view in views)
            {
              
                ToolStripMenuItem menuItem = new ToolStripMenuItem();
                _viewMenuItem.DropDownItems.Add(menuItem);
                menuItem.ShortcutKeys = view.ShortcutKeys;
                menuItem.Size = new System.Drawing.Size(180, 22);
                menuItem.Text = view.Caption;
                menuItem.ToolTipText = view.Tooltip;

                menuItem.GetCurrentParent().ImageList = UIManager.Instance.SmallImageList;
                menuItem.ImageIndex = UIManager.Instance.GetSmallImageListIndex(view.ImageHint);

                IView viewCopy = view; // for anon delegate
                menuItem.Click += delegate
                {
                    foreach (DataGridViewRow r in _viewGrid.Rows)
                    {
                        if (viewCopy.Equals(r.Tag))
                        {
                            r.Selected = true;
                            return;
                        }
                    }
                };
            }
           

        }


        public T GetView<T>() 
            where T : IView
        {
            foreach (DataGridViewRow r in _viewGrid.Rows)
            {
                if (typeof(T).IsAssignableFrom(r.Tag.GetType()))
                {
                    return (T)r.Tag;
                }
            }
            return default(T);
        }

        public void ShowView<T>() 
            where T : IView
        {
            foreach (DataGridViewRow r in _viewGrid.Rows)
            {
                if (typeof(T).IsAssignableFrom(r.Tag.GetType()))
                {
                    r.Selected = true;
                    return;
                }
            }
        }


        private void MainForm_Load(object sender, EventArgs e)
        {
            if (AuthUtils.FileSystemManager == null || !AuthUtils.FileSystemManager.IsValid)
            {
                return;
            }


            this.Text = string.Format(Properties.Messages.MainForm_Title,
                 UIConstants.ApplicationName,
                 UIConstants.ApplicationFileVersion);

            _menu.Enabled = false;
            _viewGrid.Visible = false;

            ProgressControl pc = new ProgressControl();
            UIUtils.FillWith(_viewPanel, pc);


            this.InBackground(delegate
            {
                AuthUtils.FileSystemManager.Validate(pc);

            }, delegate
            {

                this.InDisplay(delegate
                {
                    _menu.Enabled = true;
                    this.DelayLoad();
                });
            });

          

        }
    }
}

